<?php

namespace App\Services;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;

class FormValidationService
{
    /**
     * 验证并返回友好的错误消息
     */
    public static function validateWithFriendlyMessages(Request $request, array $rules, array $messages = []): array
    {
        $validator = Validator::make($request->all(), $rules, $messages);
        
        if ($validator->fails()) {
            $errors = $validator->errors();
            $friendlyErrors = [];
            
            foreach ($errors->all() as $field => $error) {
                $friendlyErrors[$field] = self::translateValidationMessage($error);
            }
            
            throw ValidationException::withMessages($friendlyErrors);
        }
        
        return $validator->validated();
    }

    /**
     * 翻译验证错误消息
     */
    protected static function translateValidationMessage(string $message): string
    {
        $translations = [
            // 必填字段
            'The :attribute field is required.' => ':attribute 是必填项',
            'The :attribute field is required when :other is present.' => '当 :other 存在时，:attribute 是必填项',
            'The :attribute field is required when :other is :value.' => '当 :other 为 :value 时，:attribute 是必填项',
            
            // 数据类型
            'The :attribute field must be a string.' => ':attribute 必须是文本',
            'The :attribute field must be an integer.' => ':attribute 必须是整数',
            'The :attribute field must be numeric.' => ':attribute 必须是数字',
            'The :attribute field must be an array.' => ':attribute 必须是数组',
            'The :attribute field must be a boolean.' => ':attribute 必须是布尔值',
            'The :attribute field must be a file.' => ':attribute 必须是文件',
            'The :attribute field must be an image.' => ':attribute 必须是图片',
            
            // 格式验证
            'The :attribute field must be a valid email address.' => ':attribute 必须是有效的邮箱地址',
            'The :attribute field must be a valid URL.' => ':attribute 必须是有效的网址',
            'The :attribute field must be a valid date.' => ':attribute 必须是有效的日期',
            'The :attribute field must be a valid IP address.' => ':attribute 必须是有效的IP地址',
            'The :attribute field must be a valid JSON string.' => ':attribute 必须是有效的JSON格式',
            
            // 长度验证
            'The :attribute field must be at least :min characters.' => ':attribute 至少需要 :min 个字符',
            'The :attribute field may not be greater than :max characters.' => ':attribute 不能超过 :max 个字符',
            'The :attribute field must be between :min and :max characters.' => ':attribute 必须在 :min 到 :max 个字符之间',
            'The :attribute field must be at least :min items.' => ':attribute 至少需要 :min 项',
            'The :attribute field may not have more than :max items.' => ':attribute 不能超过 :max 项',
            'The :attribute field must have between :min and :max items.' => ':attribute 必须在 :min 到 :max 项之间',
            
            // 数值验证
            'The :attribute field must be at least :min.' => ':attribute 不能小于 :min',
            'The :attribute field may not be greater than :max.' => ':attribute 不能大于 :max',
            'The :attribute field must be between :min and :max.' => ':attribute 必须在 :min 到 :max 之间',
            
            // 唯一性验证
            'The :attribute has already been taken.' => ':attribute 已被使用',
            'The :attribute must be unique.' => ':attribute 必须唯一',
            
            // 确认验证
            'The :attribute field must be accepted.' => '必须接受 :attribute',
            'The :attribute field must be confirmed.' => '必须确认 :attribute',
            'The :attribute field confirmation does not match.' => ':attribute 确认不匹配',
            
            // 比较验证
            'The :attribute field must be different.' => ':attribute 必须不同',
            'The :attribute field must be the same.' => ':attribute 必须相同',
            'The :attribute field must be after :date.' => ':attribute 必须在 :date 之后',
            'The :attribute field must be before :date.' => ':attribute 必须在 :date 之前',
            
            // 文件验证
            'The :attribute field must be a file.' => ':attribute 必须是文件',
            'The :attribute field must be an image.' => ':attribute 必须是图片',
            'The :attribute field must be a file of type: :values.' => ':attribute 必须是以下类型的文件：:values',
            'The :attribute field must be an image of type: :values.' => ':attribute 必须是以下类型的图片：:values',
            'The :attribute field must be at least :min kilobytes.' => ':attribute 至少需要 :min KB',
            'The :attribute field may not be greater than :max kilobytes.' => ':attribute 不能超过 :max KB',
            'The :attribute field must be between :min and :max kilobytes.' => ':attribute 必须在 :min 到 :max KB 之间',
            
            // 正则表达式验证
            'The :attribute field format is invalid.' => ':attribute 格式无效',
            'The :attribute field must match the format :format.' => ':attribute 必须符合 :format 格式',
            
            // 自定义验证规则
            'The :attribute field must be a valid phone number.' => ':attribute 必须是有效的手机号码',
            'The :attribute field must be a valid ID card number.' => ':attribute 必须是有效的身份证号码',
            'The :attribute field must be a valid postal code.' => ':attribute 必须是有效的邮政编码',
        ];

        return $translations[$message] ?? $message;
    }

    /**
     * 获取字段的中文名称
     */
    public static function getFieldName(string $field): string
    {
        $fieldNames = [
            // 用户相关
            'name' => '姓名',
            'email' => '邮箱',
            'phone' => '手机号',
            'password' => '密码',
            'password_confirmation' => '确认密码',
            'birthday' => '生日',
            'bio' => '个人简介',
            
            // 商品相关
            'title' => '标题',
            'name' => '名称',
            'description' => '描述',
            'price' => '价格',
            'original_price' => '原价',
            'sale_price' => '售价',
            'stock_quantity' => '库存数量',
            'category_id' => '分类',
            'brand' => '品牌',
            'model' => '型号',
            'sku' => '商品编码',
            'weight' => '重量',
            'dimensions' => '尺寸',
            'images' => '图片',
            'image' => '图片',
            'is_active' => '是否启用',
            'is_featured' => '是否推荐',
            
            // 订单相关
            'order_number' => '订单号',
            'status' => '状态',
            'payment_method' => '支付方式',
            'payment_status' => '支付状态',
            'shipping_method' => '配送方式',
            'tracking_number' => '物流单号',
            'shipping_company' => '物流公司',
            'receiver_name' => '收货人',
            'receiver_phone' => '收货电话',
            'receiver_address' => '收货地址',
            'notes' => '备注',
            'total_amount' => '总金额',
            'subtotal_amount' => '小计金额',
            'shipping_fee' => '运费',
            'discount_amount' => '优惠金额',
            
            // 地址相关
            'province' => '省份',
            'city' => '城市',
            'district' => '区县',
            'postal_code' => '邮政编码',
            'is_default' => '是否默认',
            
            // 售后相关
            'type' => '类型',
            'reason' => '原因',
            'description' => '详细说明',
            'refund_amount' => '退款金额',
            'quantity' => '数量',
            'condition' => '商品状态',
            'admin_comment' => '管理员备注',
            
            // 物流相关
            'company' => '物流公司',
            'code' => '公司代码',
            'website' => '官网地址',
            'sort_order' => '排序',
            
            // 系统设置相关
            'key' => '键名',
            'value' => '值',
            'group' => '分组',
            'is_public' => '是否公开',
            
            // 分类相关
            'parent_id' => '父分类',
            'sort_order' => '排序',
            'icon' => '图标',
            'color' => '颜色',
            
            // 搜索相关
            'keyword' => '关键词',
            'query' => '查询',
            'filters' => '筛选条件',
            
            // 通用字段
            'id' => 'ID',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
            'deleted_at' => '删除时间',
        ];

        return $fieldNames[$field] ?? $field;
    }

    /**
     * 处理验证异常并返回友好的错误消息
     */
    public static function handleValidationException(ValidationException $e): array
    {
        $errors = $e->errors();
        $friendlyErrors = [];

        foreach ($errors as $field => $fieldErrors) {
            foreach ($fieldErrors as $error) {
                $friendlyErrors[$field] = self::translateValidationMessage($error);
            }
        }

        return $friendlyErrors;
    }

    /**
     * 验证并返回数据，如果失败则抛出友好的验证异常
     */
    public static function validateOrFail(Request $request, array $rules, array $messages = []): array
    {
        try {
            return self::validateWithFriendlyMessages($request, $rules, $messages);
        } catch (ValidationException $e) {
            $friendlyErrors = self::handleValidationException($e);
            throw ValidationException::withMessages($friendlyErrors);
        }
    }
}
